package com.tanhua.sso.service;

import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Slf4j
@Service
public class UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    public boolean saveUserInfo(Map<String, String> param, String token) {
        //校验token
        User user = this.userService.queryUserByToken(token);
        if(null == user){
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsAnyIgnoreCase(param.get("gender"),"man") ? SexEnum.MAN:SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));

        return this.userInfoMapper.insert(userInfo) == 1;
    }

    public boolean saveUserLogo(MultipartFile file, String token) {
        //校验token
        User user = this.userService.queryUserByToken(token);
        if(null == user){
            return false;
        }

        //上传头像
        PicUploadResult uploadResult = picUploadService.upload(file);
        if("error".equals(uploadResult.getStatus())){
            log.error("上传头像失败"+"\t"+uploadResult.toString());
            return false;
        }
        //校验头像是否是人像，如果不是人像就返回false
        String filePath = uploadResult.getName();
        return this.faceEngineService.checkIsPortrait(filePath);
    }
}
